import { indexScriptDicts } from './indexVue.vue';
import {GenTableColumnEntity} from "../../entities/gen-table-cloumn.entity";

export const dialogVue = (options) => {
  const html = getFormHtmlStr(options.columns);
  const script = generateScriptSetup(options);
  return `
    ${html}
    ${script}
  `;
};

// 获取表单模板
const getFormHtmlStr = (columns) => {
  const formSlotHtmlStr = getFormSlotHtmlStr(columns);
  return `
    <template>
        <PlusDialogForm
          ref="plusFormInstance"
          v-model:visible="dialogShow"
          v-model="formData"
          :form="{ columns,  labelWidth:'110px',  labelPosition:'right',  rules:formRules }"
          :dialog="{ title: dialogTitle, width: '540px', top: '12vh', confirmLoading }"
          @confirm="handleSubmit"
          @cancel="handleCancel"
        >
          ${formSlotHtmlStr}
        </PlusDialogForm>
    </template>
  `;
};

// 获取表单自定义插槽内容
const getFormSlotHtmlStr = (columns: GenTableColumnEntity[]) => {
  const filterColumn = columns.filter((item) => {
    return item.isInsert === '1' && ['imageUpload', 'fileUpload', 'editor'].includes(item.htmlType);
  });
  let htmlStr = ``;
  filterColumn.forEach((item) => {
    let comStr = '';
    if (item.htmlType === 'editor') {
      comStr = `<editor v-model="formData.${item.javaField}" />`;
    }
    if (item.htmlType === 'fileUpload') {
      comStr = `<file-upload v-model="formData.${item.javaField}" />`;
    }
    if (item.htmlType === 'imageUpload') {
      comStr = `<image-upload v-model="formData.${item.javaField}" />`;
    }
    htmlStr += ` 
        <template #plus-field-${item.javaField}>
            ${comStr}
        </template>
    `;
  });
  return htmlStr;
};


// 获取类型对应关联属性
const getValueTypeAttr = (column: GenTableColumnEntity) => {
  let htmlStr = '';
  if (['select', 'checkbox', 'radio'].includes(column.htmlType) && column.dictType) {
    htmlStr += `options:${column.dictType}.value,
      optionsMap:{},
    `;
  }
  if (column.htmlType === 'input' && column.isInsert === '1') {
    htmlStr += `fieldProps:{
        maxlength: 200,
        modelModifiers: { trim: true },
      },
    `;
  }
  if (column.htmlType === 'textarea' && column.isInsert === '1') {
    htmlStr += `fieldProps:{
        maxlength: 200,
        showWordLimit: true,
        modelModifiers: { trim: true },
        autosize: { minRows: 2, maxRows: 4 }
      },
    `;
  }
  if (column.htmlType === 'datetime') {
    htmlStr += `
      fieldProps:{
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    `;
  }
  return htmlStr;
};



const generateScriptSetup = ({ columns, BusinessName, moduleName, businessName, primaryKey, functionName }) => {

  const dictsStr = indexScriptDicts(columns);
  const rulesStr = generateRulesData(columns);
  const columnsStr = generateColumnsData(Array.from(columns));
  const formStr = generateFormData(columns);

  return `
    <script setup>
    import { get${BusinessName}Api, add${BusinessName}Api, update${BusinessName}Api } from "@/api/${moduleName}/${businessName}";
    import { getCurrentInstance,ref } from "vue"
    const { proxy } = getCurrentInstance();
    ${dictsStr}
    
    const primaryKey = "${primaryKey}"  // 主键
    const emit = defineEmits(["update"]);
    
    const dialogShow = ref(false);
    const confirmLoading = ref(false)
    const isEdit = computed(() =>!!formData.value[primaryKey])
    const dialogTitle = computed(() => (isEdit.value ? '编辑' : '新增')+'${functionName}')
    const plusFormInstance = ref(null);
    const formInstance = computed(()=>plusFormInstance.value?.formInstance)
    const columns = computed(()=>${columnsStr})
    const formData = ref({ 
      ${formStr}
    });
    const formRules = ref({ 
      ${rulesStr}
    });
    
    // 确定按钮操作
    const handleSubmit = async () => {
      try {
        confirmLoading.value = true
        if (isEdit.value) {
          await update${BusinessName}Api(formData.value)
          proxy.$modal.msgSuccess("修改成功")
        } else {
          await add${BusinessName}Api(formData.value)
          proxy.$modal.msgSuccess("新增成功")
        }
        handleCancel();
        emit('update')
      } catch (error) {
        console.warn('提交错误:', error)
      } finally {
        confirmLoading.value = false
      }
    }
    
    // 取消按钮操作
    function handleCancel() {
      dialogShow.value = false
      onReset();
    }
    
    // 重置数据
    const onReset = () => {
      formData.value = {
        ${formStr}
      }
      formInstance.value.resetFields();
    }
    // 查询回显
    const getDetail = async (key) => {
      const { data } = await  get${BusinessName}Api(key)
      formData.value = data;
    }
    // 打开弹框
    const openDialog = async (row) => {
      if(row && row[primaryKey]){
        await getDetail(row[primaryKey])
      }
      dialogShow.value = true;
    };
    defineExpose({ openDialog });
    </script>
  `;
};

// 获取类型
const getValueType = (column: GenTableColumnEntity) => {
  // 控件枚举
  const obj = {
    input: 'input',
    textarea: 'textarea',
    select: 'select',
    radio: 'radio',
    checkbox: 'checkbox',
    datetime: 'date-picker',
  };
  const val = obj[column.htmlType];
  if (val) {
    return `valueType:'${val}',`;
  }
  return '';
};



// 生成列信息
const generateColumnsData = (columns: GenTableColumnEntity[]) => {
  let str = `[`;
  columns.filter(col=>col.isInsert === '1' || col.isEdit === '1').forEach((item) => {
    str += `{
      label: '${item.columnComment}',
      prop: '${item.javaField}',
      ${getValueType(item)}
      ${getValueTypeAttr(item)}
    },`;
  });
  str += `]`;
  return str;
};

const generateFormData = (columns) => {
  return columns
    .filter((item) => item.isInsert === '1' && item.isPk === '0')
    .map((item) => `${item.javaField}: ${item.htmlType === 'checkbox' ? '[]' : '""'}`)
    .join(',\n');
};

//  生成验证规则
const generateRulesData = (columns) => {
  return columns
      .filter((item) => item.isRequired === '1')
      .map((item) => {
        let trigger = '"blur"';
        if (['select', 'radio', 'checkbox'].includes(item.htmlType)) {
          trigger += ',"change"';
        }
        return `${item.javaField}: [{ required: true, message: "${item.columnComment}不能为空", trigger: [${trigger}] }]`;
      })
      .join(',\n');
};
